#-*- coding:utf-8 -*-
'''
Created on 2013-6-20

@author: hanjiewu
'''

import urllib, urllib2
import datetime
import logging

TOKEN_URL = "http://gyadmin.wsd.com/admin/tools/api/token_key.jsp"
SCHEDULER_JOB_URL = " http://gyadmin.wsd.com/admin/tools/api/scheduler_job_api.jsp"
                    
class SchedulerJob(object):
    '''
    classdocs
    '''
    

    def __init__(self, name, author, url, method, startTime=datetime.datetime.now() , parameters={}, cookies={}):
        '''
        设置基本信息之后，调用simpleScheduler或cronScheduler设置执行的频率
        name: 名称
        author: 提交者
        url: 请求的连接
        method: 请求的方式
        parameters：请求的参数
        cookies：请求的cookie信息
        '''
        self.name = name
        self.author = author
        self.url = url
        self.method = method
        # 默认就执行一次
        self.simpleScheduler()
        self.parameters = parameters
        self.cookies = cookies
        self.startTime = startTime 
    
    # 默认
    def simpleScheduler(self, count=1, unit=3, interval=1):
        self.schedulerMethod = SchedulerMethod.SIMPLE_SCHEDULER
        self.count = count
        self.unit = unit
        self.interval = interval
        pass
    
    def cronScheduler(self, cronExpression):
        self.schedulerMethod = SchedulerMethod.CRON_SCHEDULER
        self.cronExpression = cronExpression
    
    def addParameter(self, name, value):
        self.parameters[name] = value
    
    def addCookie(self, name, value):
        self.cookies[name] = value
    
    def scheduler(self):
        file = urllib.urlopen(TOKEN_URL)
        token = file.readline()
        file.close()
        
        logging.warn(token)
        cgiParameters = {'name': self.name, 'method': self.method, 'url':self.url, \
                         'author':self.author, 'token':token, 'startTime':self.startTime.strftime('%Y-%m-%d %H:%M:%S')}
        cgiParameters['schedulerMethod'] = self.schedulerMethod.type
        if self.schedulerMethod == SchedulerMethod.SIMPLE_SCHEDULER:
            cgiParameters.update({'count': self.count, 'unit': self.count, 'intervals':self.interval})
        else:
            cgiParameters['cronExpression'] = self.cronExpression
        f = urllib2.urlopen(SCHEDULER_JOB_URL, urllib.urlencode(cgiParameters))
        ret = f.readline()
        f.close()
        logging.warn(ret)
        return eval(ret)['r']
        
        
class SchedulerMethod(object):
    
    def __init__(self, type):
        self.type = type
        
SchedulerMethod.SIMPLE_SCHEDULER = SchedulerMethod(1)
SchedulerMethod.CRON_SCHEDULER = SchedulerMethod(2)

if __name__ == '__main__':
    schedulerJob = SchedulerJob('python_测试', 'hanjiewu', 'http://soso.com', 'GET')
    schedulerJob.scheduler()
